package com.yongqi.duocai.controller;

import com.yongqi.duocai.entity.User;
import com.yongqi.duocai.entity.result.UserResult;
import com.yongqi.duocai.exception.ResponseEnum;
import com.yongqi.duocai.service.UserService;
import com.yongqi.duocai.utils.JsonResult;
import com.yongqi.duocai.utils.JwtUtils;
import com.yongqi.duocai.utils.NoteUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 1.描述（@desc）：登陆控制层
 * 2.作者（@author）：夏亮辉
 * 3.日期（@date）：2021年06月19  12:59
 * 4.版本（@version）：1.0.0
 * 5.版权：
 */

@RestController
@Api(tags = "LoginController")
public class LoginController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserService userService;

    @PostMapping("/getCode")
    @ApiOperation(value = "获取验证码")
    public JsonResult getCode(String phone){
        JsonResult jsonResult = new JsonResult();

        // 生成验证码
        String code = NoteUtils.productCode();
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

        HashMap<String, String> map = new HashMap<>();
        map.put("code", code);

        boolean res = NoteUtils.sendMessage(phone,map);

        if(res){
            jsonResult.setCode(200);
            jsonResult.setMessage("验证码发送成功！");
        }else {
            jsonResult.setCode(304);
            jsonResult.setMessage("验证码发送失败！！");
        }
        return jsonResult;
    }

    @PostMapping("/login")
    @ApiOperation(value = "验证码登陆")
    public JsonResult login(String phone, String code){
        User user = new User();
        boolean save = false;
        // 根据登陆的手机号查询用户
        User condition = userService.selectByPhone(phone);
        Integer userId = -1;
        if(condition == null){
            // 将该手机号写入数据库
            user.setWxName(phone);
            user.setPhone(phone);
            save = userService.save(user);
            userId = user.getId();
        }else {
            userId = condition.getId();
        }

        JsonResult jsonResult = new JsonResult();
        String answer = (String) redisTemplate.opsForValue().get(phone);
        if(answer == null || answer.equals("null")){
            jsonResult.setMessage("验证码不合法！请重新获取。");
        }else if((!answer.equals(code))){
            jsonResult.setMessage("验证码输入错误!请重试");
        } else {
            String res = answer.toString();
            if(res.equals(code)){
                // 转装返回对象
                UserResult userResult = new UserResult();
                userResult.setUserId(userId);
                userResult.setToken(JwtUtils.createToken(userId));
                jsonResult.setCode(200);
                jsonResult.setData(userResult);
                jsonResult.setMessage("登录成功");
            }
        }
        return jsonResult;
    }

    @ApiOperation("校验令牌")
    @GetMapping("/checkToken")
    public JsonResult checkToken(HttpServletRequest request){
        JsonResult jsonResult = new JsonResult();
        String token = request.getHeader("token");
        Integer userId = Integer.parseInt(request.getHeader("userId"));
        boolean result = JwtUtils.checkToken(token, userId);
        if(result){
           jsonResult.setCode(200);
           jsonResult.setMessage("校验成功");
        }else {
           jsonResult.setResponse(ResponseEnum.LOGIN_AUTH_ERROR);
        }
        return jsonResult;
    }

    @PostMapping("/loginOut")
    @ApiOperation(value = "退出登陆- 主要是记录用户退出的时间")
    public JsonResult loginOut(Integer id){
        JsonResult jsonResult = new JsonResult();
        User user = userService.selectById(id);
        user.setLastTime(LocalDateTime.now());
        boolean res = userService.updateById(user);
        if(res){
            jsonResult.setCode(200);
            jsonResult.setMessage("退出成功");
        }
        return jsonResult;
    }

}
